package com.maimao.auth.mobilecCode;

import com.maimao.core.constant.GrantTypeEnum;
import com.maimao.core.utils.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 手机验证码授权
 * @author MaoLin Wang
 * @date 2020/12/13 11:01 下午
 */
public class MobileCodeTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = GrantTypeEnum.MOBILE_CODE.getType();
    private static final int CODE_LENGTH = 5;
    private final AuthenticationManager authenticationManager;

    public MobileCodeTokenGranter(AuthorizationServerTokenServices tokenServices,
                                  ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, final AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }


    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client,
                                                           TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("username");  //客户端提交的用户名 这里为手机号
        if (!RegexUtils.checkPhone(mobile)) {
            throw new InvalidGrantException("手机号码格式错误");
        }
        String code = parameters.get("code");  //客户端提交的验证码
        if (StringUtils.isEmpty(code) || code.length() != CODE_LENGTH) {
            throw new InvalidGrantException("验证码错误");
        }
        Authentication userAuth = new MobileCodeAuthenticationToken(mobile, code);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

        try {
            //调用手机验证的Provider
            userAuth = authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException ase) {
            throw new InvalidGrantException(ase.getMessage());
        } catch (BadCredentialsException e) {
            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user with mobile: " + mobile);
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
